<template>
<a-modal
    :visible="visible"
    v-if="visible"
    title="添加导出模板"
    width="80%"
    :destroyOnClose="true"
    :getContainer="false"
    :style="{position: 'absolute'}"
    @cancel="visible = false"
    @ok="submit"
>
<a-row class="grid-demo" style="marginBottom: 16px; backgroundColor:#fff">
    <a-col :span="8">
        <ma-form v-model="form" :options="options" :columns="columnsOptions" ref="crudForm" :submitShowBtn="false" />
    </a-col>
    <a-col :span="1"></a-col>
    <a-col :span="15">
        <a-space>
            <span>注：勾选需要导出的字段</span>
        </a-space>
        <a-table 
            :columns="columns" 
            :data="data"
            :row-selection="{type: 'checkbox'}"
            @select="handleSelect"
            @change="handleChange"
            :pagination="false"
            :scroll="{y:300}"
            :scrollbar="true"
            :selected-keys="selected"
            row-key="value"
            :draggable="{}">
            <template #title="{ record }">
                <a-input v-model="record.title" />
            </template>
            <template #column_no="{ record }">
                <a-input type="number" v-model="record.column_no" @change="handleUpdate(record)" />
            </template>
        </a-table>
    </a-col>
  </a-row>
</a-modal>
</template>

<script setup lang="ts">
import {inject, reactive, ref,watch} from "vue";
import templateExcelObject from "@/api/template/templateExcelObject";
import templateExcelExport from "@/api/template/templateExcelExport";
import { Message } from '@arco-design/web-vue'
import { auth, role } from '@/utils/common'
const visible = ref(false)
const crudForm = ref()
const parentCrudForm = inject('crudRef',{})
const tableList = inject('tableList');
const form = ref({})
const selected = ref([])
const options = ref({
    submitShowBtn:false,
    resetShowBtn:false,
})
const props = defineProps({
    config: {
        default: {}
    },
})
const columnsOptions = reactive([
    {
        title: '模板名称',
        dataIndex: 'name',
        rules:{required:true, message:'请输入模板名称'},
    },
    {
    title: "类型",
    dataIndex: "type",
    formType: "radio",
    type:'button',
    rules:{required:true, message:'请选择类型'},
    dict: {
      data:[
        {label:'客户',value:"1"},
        {label:'员工',value:"2"},
      ],
      translation: true
    }
  },
  {
    title: "系统模板",
    dataIndex: "system_template",
    formType: "switch",
    commonRules: {
      required: true,
      message: "请输入系统模板"
    },
    display:false,
    checkedValue: 1,
    uncheckedValue: 0,
    customRender: ({record}) => {
      return record.system_template == 1 ? '是' : '否'
    }
  },
  {
    title: "导出类型",
    dataIndex: "export_main_object_name",
    formType: "cascader",
    rules:{required:true, message:'请选择导出类型'},
    dict: {
      url:'template/excelObject/list',
      props: {
        label: 'name',
        value: 'id',
        parentId:'parent_id'
      },
      params:{dto:props.config.type},
      translation: true
    },
    onChange: async (val)=>{
       await getField(val) 
    }
  },
])

const getField = async (val)=>{
    if(!val){
        return
    }
    let res = await templateExcelObject.dtoFields({dto:val,template_excel_export_id:form.value.id})
        if(res.success){
            init(res.data)
        }
}

const columns = reactive([
{
    title: '字段',
    dataIndex: 'label',
},
{
    title: '表头',
    dataIndex: 'title',
    slotName: 'title',
},
{
    title: '排序',
    dataIndex: 'column_no',
    slotName: 'column_no',
},
]);
const params = ref([])
const data = ref();
const init = (_data) =>{
    let tmp = []
    let column_no = form.value.detail.length
    let select = []
    console.log(form.value)
    for(let i = 0 ; i < form.value.detail.length ; i++){
        let d = form.value.detail[i]
        let t = {value: d.path, label: '', column_no:String(i+1),title:d.title_name}
        tmp.push(t)
        params.value.push(t)
        select.push(d.path)
    }
    for(let i = 0 ; i < _data.length ; i++){
        if(select.includes(_data[i].value)){
            tmp.map(j=>{
                if(j.value == _data[i].value){
                    j.label = _data[i].label
                }
            })
        }else{
            column_no++
            _data[i].column_no = String(column_no)
            _data[i].title = _data[i].label
            tmp.push(_data[i]);
        }
    }
    data.value = tmp
    selected.value = select
}

const handleUpdate = (record)=>{
    data.value.sort((i,j)=>{
        return i.column_no - j.column_no
    })
    data.value.map((i,k)=>{
        i.column_no = String(k+1)
    })
}

const handleChange = (_data)=>{
    _data.map((i,k)=>{
        i.column_no = String(k+1)
    })
   data.value = _data

}

const handleSelect = (_data) => {
    selected.value = _data
    params.value = []
    data.value.map(i=>{
        if(_data.includes(i.value)){
            params.value.push(i)
        }
    })
}
const open = (record) =>{
    selected.value = []
    data.value = []
    if(record){
        form.value = record
        record.type = String(record.type)
        getField(record.export_main_object_name)
    }else{
        form.value = {type:'2', export_main_object_name:null,detail:[]}
    }
    columnsOptions[1].display = auth('template:excelExport:system') && props.config.type
    columnsOptions[2].display = auth('template:excelExport:system') && props.config.type
    visible.value = true
}

const submit = async () =>{
    if(!form.value.name){
        Message.error('请输入模板名称')
        return
    }
    if(!form.value.export_main_object_name){
        Message.error('请选择导出类型')
        return
    }
    if(!params.value.length){
        Message.error('请选择导出字段')
        return
    }
    let res = await templateExcelExport.save({info:form.value,detail:params.value})
    if(tableList){
        tableList()
    }else if(parentCrudForm){
        parentCrudForm.value.refresh()
    }
    if(res.success){
        Message.success('保存成功')
        visible.value = false
    }
}

defineExpose({open})
</script>